/**
 * 
 */
package core;

import java.awt.geom.Rectangle2D;
import java.util.HashSet;
import java.util.Set;

import util.Constants;
import NET.sourceforge.BplusJ.BplusJ.BplusTree;

/**
 * 
 * @author Xiaohui
 * @version 0.1 Set of object id's is added
 * 
 */
public class Partition extends Rectangle2D.Double implements Constants {
	String treefile = "D:/Research/parinet/meta/b+tree.txt"; // default one
	String blockfile = "D:/Research/parinet/meta/b+block.txt";
	Set<Integer> oidList;

	static String samplekey = "205902321";
	BplusTree bpt;

	public void addOid(int oid) {
		this.oidList.add(oid);
	}

	/**
	 * @param oid
	 * @return true if the list contains
	 */
	public boolean search(int oid) {
		return this.oidList.contains(oid);
	}

	/**
	 * @param treeFile
	 * @param blockFile
	 * @throws Exception
	 */
	public Partition(String treeFile, String blockFile) throws Exception {
		super.setRect(0, 0, 0, 0);

		this.treefile = treeFile;
		this.blockfile = blockFile;
		bpt = BplusTree.Initialize(treeFile, blockFile, samplekey.length(),
				INVARIANTCULTUREID, nodesize, buffersize);
		oidList = new HashSet<Integer>();
	}

	public Partition(String treeFile, String blockFile, double x, double y,
			double w, double h) throws Exception {
		super(x, y, w, h);
		this.treefile = treeFile;
		this.blockfile = blockFile;
		bpt = BplusTree.Initialize(treeFile, blockFile, samplekey.length(),
				INVARIANTCULTUREID, nodesize, buffersize);
		oidList = new HashSet<Integer>();
	}

	private Partition(double x, double y, double w, double h) {
		super(x, y, w, h);
		this.treefile = null;
		this.blockfile = null;
	}

	public void insert(String key, String value) throws Exception {
		bpt.Set(key, value);
	}

	public String get(String key) throws Exception {
		return bpt.get(key);
	}

	public void commit() throws Exception {
		bpt.Commit();
	}

	public void abort() throws Exception {
		bpt.Abort();
	}

	public String getTreeFileName() {
		return treefile;
	}

	public String getBlockFileName() {
		return blockfile;
	}

	public String toString() {
		String str = super.toString() + " <";
		for (int oid : oidList) {
			str += oid + ",";
		}
		str += ">";
		return str;
	}

	public static Partition reOpen(String treeFile, String blockFile, double x,
			double y, double w, double h) throws Exception {
		Partition p = new Partition(x, y, w, h);
		p.treefile = treeFile;
		p.blockfile = blockFile;
		p.bpt = BplusTree.ReadOnly(treeFile, blockFile);
		p.oidList = new HashSet<Integer>();

		return p;
	}
}
